package com.treasure.mall.zbqmallapi.controller;

import com.alibaba.fastjson.JSON;
import com.treasure.mall.biz.config.tencent.TencentConfig;
import com.treasure.mall.biz.entity.live.LiveRoomPO;
import com.treasure.mall.biz.remote.live.TencentIMService;
import com.treasure.mall.biz.remote.live.TencentLiveService;
import com.treasure.mall.biz.service.core.live.LiveRoomService;
import com.treasure.mall.biz.service.core.live.LiveSessionService;
import com.treasure.mall.zbqmallapi.dto.IMNotifyData;
import com.treasure.mall.zbqmallapi.dto.LiveEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.controller
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/13 14:15
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.zbqmallapi.controller Inc. All rights reserved.
 */
@Slf4j
@RestController
public class TencentNotifyController {
    @Resource
    private LiveRoomService liveRoomService;
    @Resource
    private LiveSessionService liveSessionService;
    @Resource
    private TencentLiveService tencentLiveService;
    @Resource
    private TencentConfig tencentConfig;
    @Autowired
    private TencentIMService tencentIMService;

    @Autowired
    private ThreadPoolTaskScheduler scheduler;

    /**
     * 直播回调通知
     * https://cloud.tencent.com/document/product/267/32744#.E5.85.AC.E5.85.B1.E5.8F.82.E6.95.B0.E8.AF.B4.E6.98.8E
     *
     * @param data
     * @return
     */
    @RequestMapping("/tencent/notify/live")
    public Object liveNotify(@RequestBody LiveEvent data) {
        Map<String, Object> map = new HashMap<>();
        long lastTime = System.currentTimeMillis() / 1000 - 10 * 60;
        if (data.getTime() < lastTime) {
            map.put("code", 0);
            return map;
        }
        String domain = tencentConfig.getLivePushDomain();
        if (data.getApp() != null && !data.getApp().equals(domain)) {
            log.warn("received live event with illegal push domain:" + data.getApp() + ",domain:" + domain);
            map.put("code", 0);
            return map;
        }

        if (!domain.equals(tencentConfig.getLivePushDomain())) {
            map.put("code", 0);
            return map;
        }

        String key = tencentConfig.getLiveNotifyKey();
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            map.put("code", 0);
            return map;
        }

        String _tem = key + data.getTime();
        String result = Hex.encodeHexString(md.digest(_tem.getBytes()));
        if (!result.toLowerCase().equals(data.getSign().toLowerCase())) {
            throw new IllegalArgumentException("received live event with illegal sign");
        }
        switch (data.getEventType()) {
            case 0:
                //如果发生网络斗断,5分钟后，关闭直播间
                log.info("断流回调参数：" + JSON.toJSONString(data));
//                boolean pass = data.getErrcode() == 7 || data.getErrcode() == 4;
//                if (data.liveRoomId() != null && pass) {
//                    scheduler.schedule(() -> stopLive(data.liveRoomId()), Jsr310Utils.DateTime.toDate(LocalDateTime.now().plusMinutes(5)));
//                }
                break;
            case 1:
                break;
        }
        map.put("code", 0);
        return map;
    }


    private void stopLive(Long roomId) {
        try {
            LiveRoomPO room = liveRoomService.findById(roomId);
            if (room != null && room.getSessionId() != null) {

                liveSessionService.stop(room.getSessionId());
                tencentLiveService.closeStream(room);

//                // 发送停止直播消息
//                tencentIMService.sendLiveStateChangeMessage(LiveStateMessageDTO.builder()
//                        .messageType(MessageType.stopPush)
//                        .roomId(roomId)
//                        .build()
//                );
            }

        } catch (Exception e) {
            log.error("/tencent/notify/live 断流回调失败");
        }
    }


    /**
     * IM
     * * 参数
     * * * CallbackCommand: Group.CallbackAfterNewMemberJoin
     * * * ClientIP:115.204.89.156
     * * * OptPlatform:iOS
     * * * SdkAppid:1400377136
     * * * contenttype:json
     *
     * @param appId
     * @param command     Group.CallbackAfterNewMemberJoin
     * @param requestData
     * @return
     */
    @PostMapping("/tencent/notify/im")
    public ResponseEntity<String> message(@RequestParam(value = "SdkAppid") String appId,
                                          @RequestParam("CallbackCommand") String command,
                                          @RequestBody IMNotifyData requestData) {

        String systemAppId = tencentConfig.getImSdkAppId();
        if (appId != systemAppId) {
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body("{\"ActionStatus\": \"OK\",\"ErrorInfo\": \"\",\"ErrorCode\": 0\n}");
        }
        switch (command) {
            case "Group.CallbackAfterNewMemberJoin":
                joinGroup(requestData);
                break;
            case "Group.CallbackAfterMemberExit":
                leaveGroup(requestData);
                break;
        }
        return ResponseEntity
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body("{\"ActionStatus\": \"OK\",\"ErrorInfo\": \"\",\"ErrorCode\": 0\n}");


    }

    /**
     * 离开房间
     *
     * @param data
     */
    private void leaveGroup(IMNotifyData data) {
//        if (!data.getType().equals("AVChatRoom")) {
//            return;
//        }
    }

    /**
     * 加入房间
     *
     * @param data
     */
    private void joinGroup(IMNotifyData data) {
//        if (!data.getType().equals("AVChatRoom")) {
//            return;
//        }
//        if (!data.getJoinType().equals("Apply")) {
//            return;
//        }
    }
}
